package com.android.dumiaogou.fragment;


import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.dumiaogou.MainActivity;
import com.android.dumiaogou.R;
import com.android.dumiaogou.activity.BaseObject;
import com.android.dumiaogou.activity.MainTab;
import com.android.dumiaogou.activity.mine.DataEditActivity;
import com.android.dumiaogou.activity.mine.LoginActivity;
import com.android.dumiaogou.activity.mine.NewGuideActivity;
import com.android.dumiaogou.activity.mine.ScoreSignInActivity;
import com.android.dumiaogou.activity.mine.TakeOverAddressActivity;
import com.android.dumiaogou.activity.mine.VerifyIdCardActivity;
import com.android.dumiaogou.model.member.CheckIDCardData;
import com.android.dumiaogou.model.member.CheckIDCardDataCallback;
import com.android.dumiaogou.model.member.MemberInfoData;
import com.android.dumiaogou.model.member.MemberInfoDataCallback;
import com.android.dumiaogou.model.member.MessageIndexData;
import com.android.dumiaogou.model.member.MessageIndexDataCallback;
import com.android.dumiaogou.utils.ConstantsUrl;
import com.android.dumiaogou.utils.HttpUtils;
import com.android.dumiaogou.utils.LoginState;
import com.android.dumiaogou.utils.MyLog;
import com.android.dumiaogou.utils.ObjectUtils;
import com.android.dumiaogou.view.dialog.MainMsg;
import com.elbbbird.android.socialsdk.SocialSDK;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static com.android.dumiaogou.R.id.mine_exit;

/**
 * 个人中心
 */
public class Fragment4 extends Fragment implements MainActivity.DataChange {

    @BindView(R.id.user_avatar)
    ImageView userAvatar;
    @BindView(R.id.user_name)
    TextView userName;
    @BindView(R.id.num_all)
    TextView numAll;
    @BindView(R.id.money_auction)
    TextView money_auction;
    @BindView(R.id.money_sending)
    TextView money_sending;
    @BindView(R.id.myscore)
    TextView myscore;
    @BindView(R.id.num_auctioning_now)
    TextView num_Auctioning_now;
    @BindView(R.id.num_auctioning_mine)
    TextView num_Auctioning_mine;
    @BindView(R.id.num_waiting_aucton)
    TextView numWaiting_aucton;
    @BindView(R.id.num_mine_obligation)
    TextView numMine_obligation;
    @BindView(R.id.num_msg)
    TextView num_msg;
    @BindView(mine_exit)
    Button mineExit;
    @BindView(R.id.click_resetnetwork)
    LinearLayout clickResetnetwork;
    @BindView(R.id.progress)
    RelativeLayout progress;
    @BindView(R.id.no_data)
    RelativeLayout noData;
    @BindView(R.id.no_data_tv)
    TextView noDataTv;
    @BindView(R.id.set_setting)
    ImageView set_setting;
    private FragmentActivity mcontext;
    private View view;

    private boolean networkConnected;
    private String login_type;
    private String commission;
    private String nickname;
    private String photo;
    private String mobile;
    private String sexy;
    private AlertDialog dialog;
    private static boolean isChecked;
    private String coin;
    private String free_coin;

    public Fragment4() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_fragment4, container, false);
        ButterKnife.bind(this, view);
        mcontext = getActivity();
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        //((MainActivity) mcontext).setData(this);
        return view;
    }

    @Override
    public void onStart() {
        super.onStart();
        initData();
        if(!isChecked){
            isChecked =true;
            checkIDCard();
        }
    }

    @Override
    public void setDataChange(int curr) {
        initData();
    }

    private void initData() {

        if (LoginState.getInstance().isLogin(mcontext)) {
            nickname = LoginState.getInstance().getUserInfo(mcontext, 0);
            photo = LoginState.getInstance().getUserInfo(mcontext, 1);
            login_type = LoginState.getInstance().getUserInfo(mcontext, 3);
            userName.setText(nickname);
            ObjectUtils.photoCircle(mcontext, photo, userAvatar);
            mineExit.setVisibility(View.VISIBLE);
            GetDataNumber();
            GetMessageNumber();

        } else {
            unloginUI();
        }


    }

    private void unloginUI() {
        ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
        mineExit.setVisibility(View.GONE);
        userName.setText("未登录");
        userAvatar.setImageResource(R.mipmap.avater);
        money_auction.setText("0");
        money_sending.setText("0");
        myscore.setText("0");
        numAll.setVisibility(View.INVISIBLE);
        num_Auctioning_now.setVisibility(View.INVISIBLE);
        num_Auctioning_mine.setVisibility(View.INVISIBLE);
        numWaiting_aucton.setVisibility(View.INVISIBLE);
        numMine_obligation.setVisibility(View.INVISIBLE);
        num_msg.setVisibility(View.INVISIBLE);
    }

    private void checkIDCard() {
        String address = ConstantsUrl.domain + ConstantsUrl.MEMBER_CHECKIDCARD;
        MyLog.e("地址", address);
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        if (networkConnected) {
            HashMap<String, String> header = ObjectUtils.getHeader(mcontext);
            HttpUtils.get(address, header, null, callback);
        }
    }

    CheckIDCardDataCallback callback = new CheckIDCardDataCallback() {
        @Override
        public void onError(Call call, Exception e, int id) {
        }

        @Override
        public void onResponse(CheckIDCardData response, int id) {
            if (response.getCode() == 0) {
                if(response.getData()!=null&&response.getData().getStatus()==1){
                    showVerifyDialog();
                }
            }
        }
    };

    private void showVerifyDialog() {
        LayoutInflater inflater = (LayoutInflater) mcontext
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View v = inflater.inflate(R.layout.dialog_verify_idcard, null);
        TextView sure = (TextView) v.findViewById(R.id.dialog_sure);
        ImageView close = (ImageView) v.findViewById(R.id.dialog_close);
        close.setOnClickListener(new View.OnClickListener() {
                                     @Override
                                     public void onClick(View view) {
                                         dialog.dismiss();
                                     }
                                 }
        );
        sure.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        startActivity(new Intent(mcontext, VerifyIdCardActivity.class));
                                        dialog.dismiss();
                                    }
                                }
        );
        dialog = new AlertDialog.Builder(mcontext).setView(v).setCancelable(true).show();
    }

    private void GetMessageNumber() {
        String address = ConstantsUrl.domain + ConstantsUrl.MEMBERMESSAGEINDEX;
        MyLog.e("地址", address);
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        if (networkConnected) {
            HashMap<String, String> header = ObjectUtils.getHeader(mcontext);
            HttpUtils.get(address, header, null, new MessageIndexDataCallback() {

                @Override
                public void onError(Call call, Exception e, int id) {
                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
                }

                @Override
                public void onResponse(MessageIndexData response, int id) {
                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);

                    if (response.getCode() == 0) {
                        String messagenumber = response.getList().size()+"";
                        //消息数量
                        if (response.getList().size()==0) {

                            num_msg.setVisibility(View.INVISIBLE);

                        } else {
                            num_msg.setVisibility(View.VISIBLE);
                            num_msg.setText(messagenumber);
                        }

                    } else {
                        if(response.getCode() == 40001){
                            unloginUI();
                            ObjectUtils.reLogin(mcontext);
                        }

                    }
                }

            });
        } else {
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
        }


    }

    //
    private void GetDataNumber() {
        String address = ConstantsUrl.domain + ConstantsUrl.MEMBERORDINGDANGNUM;
        MyLog.e("地址", address);
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        if (networkConnected) {
            HashMap<String, String> header = ObjectUtils.getHeader(mcontext);
            HttpUtils.get(address, header, null, new MemberInfoDataCallback() {

                @Override
                public void onError(Call call, Exception e, int id) {
                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
                }

                @Override
                public void onResponse(MemberInfoData response, int id) {
                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);

                    if (response.getCode() == 0) {
                        nickname = response.getData().getUsername();
                        photo = response.getData().getPhoto();
                        mobile = response.getData().getMobile();
                        sexy = response.getData().getSex();
                        UpdataInfo(nickname, photo, response.getData().getMid());
                        userName.setText(nickname);
                        coin = response.getData().getCoin();
                        money_auction.setText(coin);
                        free_coin = response.getData().getFree_coin();
                        money_sending.setText(free_coin);
                        myscore.setText(response.getData().getScore());
                        ObjectUtils.photoCircle(mcontext, photo, userAvatar);
//                        //消息数量
//                        if (response.getData().getMsgUnreadCount().equals("0")) {
//
//                            num_msg.setVisibility(View.INVISIBLE);
//
//                        } else {
//
//                            num_msg.setVisibility(View.VISIBLE);
//                            num_msg.setText(response.getData().getMsgUnreadCount() + "");
//                        }

                    } else {
                        if(response.getCode() == 40001){
                            unloginUI();
                            ObjectUtils.reLogin(mcontext);
                        }
                    }
                }
            });
        } else {
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
        }
    }

    private void UpdataInfo(String uname, String avatar, String uid) {
        SharedPreferences sp = mcontext.getSharedPreferences(ConstantsUrl.USERDATA, 0);
        SharedPreferences.Editor edit = sp.edit();
        edit.putString(ConstantsUrl.USERDATA_NAME, uname);
        edit.putString(ConstantsUrl.USERDATA_AVATAR, avatar);
        edit.putString(ConstantsUrl.USERDATA_UID, uid);
        edit.commit();
    }

    @OnClick({R.id.user_avatar, R.id.message, R.id.mine_auction_all, R.id.mine_all, R.id.mine_auctioning_now,
            R.id.mine_auctioning_mine, R.id.mine_waiting_aucton, R.id.mine_obligation, mine_exit,
            R.id.click_resetnetwork_refresh, R.id.mine_shopping_address,R.id.set_setting,R.id.mine_sign_in,
            R.id.mine_directbuy_order,R.id.mine_mer_voucher,R.id.mine_service_centre, R.id.mine_invitation, R.id.mine_verify,
            R.id.mine_newer_guide,R.id.mine_share_bill,R.id.ll_coin,R.id.ll_free_coin,R.id.ll_free_sorce,R.id.recharge
    })
    public void onClick(View view) {

        Intent intent_data = new Intent(mcontext, DataEditActivity.class);
        switch (view.getId()) {

            case R.id.user_avatar:
                if (LoginState.getInstance().isLogin(mcontext)) {
                    intent_data.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_MEMBER_DATAEDIT_AVATAR, photo);
                    intent_data.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_MEMBER_DATAEDIT_NICK, nickname);
                    intent_data.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_MEMBER_DATAEDIT_PHONE, mobile);
                    intent_data.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_MEMBER_DATAEDIT_SEXY, sexy);
                    startActivity(intent_data);
                } else {
                    startActivity(new Intent(mcontext, LoginActivity.class));
                }
                break;
            case R.id.user_ll:
                if (LoginState.getInstance().isLogin(mcontext)) {

                    return;
                }
                startActivity(new Intent(mcontext, LoginActivity.class));
                break;
            case R.id.message:
                ToOrder(0,10);
                break;
            case R.id.set_setting:
                if (LoginState.getInstance().isLogin(mcontext)) {
                    ToObject("设置", 0);
                } else {
                    startActivity(new Intent(mcontext, LoginActivity.class));
                }
                break;
            case R.id.recharge:
                MainActivity A = (MainActivity) getActivity();
                A.ChangeMainFragment(1);
                break;
            case R.id.mine_auction_all:
                ToOrder(0, 4);
                break;
            case R.id.mine_all:
                ToOrder(0, 4);
                break;
            case R.id.mine_auctioning_now:
                ToOrder(1, 4);
                break;
            case R.id.mine_auctioning_mine:
                ToOrder(2, 4);
                break;
            case R.id.mine_waiting_aucton:
                ToOrder(3, 4);
                break;
            case R.id.mine_obligation:
                ToOrder(4, 4);
                break;
//            case R.id.mine_remark:
//                ToOrder(5, 4);
//                break;
            case R.id.mine_mer_voucher:
                ToOrder(0, 9);
                break;
            case R.id.mine_group:
                ToOrder(0, 5);
                break;

            case R.id.mine_collect:
                ToOrder(0, 6);
                break;
            case R.id.mine_coupon:
                ToOrder(0, 7);
                break;
            case R.id.mine_shopping_address:
                if (LoginState.getInstance().isLogin(mcontext)) {
                    Intent intent_q = new Intent(getActivity(), TakeOverAddressActivity.class);
                    startActivity(intent_q);
                } else {
                    startActivity(new Intent(mcontext, LoginActivity.class));
                }
                break;
            case R.id.mine_sign_in:
                if (LoginState.getInstance().isLogin(mcontext)) {
                    Intent intent_q = new Intent(getActivity(), ScoreSignInActivity.class);
                    startActivity(intent_q);
                } else {
                    startActivity(new Intent(mcontext, LoginActivity.class));
                }
                break;
            case R.id.mine_rank:
                if (LoginState.getInstance().isLogin(mcontext)) {
                    ToObject("拼团王", 0);
                } else {
                    startActivity(new Intent(mcontext, LoginActivity.class));
                }
                break;
            case R.id.mine_fans:
                if (LoginState.getInstance().isLogin(mcontext)) {
                    ToObject("我的粉丝", 0);
                } else {
                    startActivity(new Intent(mcontext, LoginActivity.class));
                }
                break;
            case R.id.mine_question:
                ToObject("", 1);
                break;
            case R.id.mine_about:
                ToObject("关于我们", 0);
                break;
            case R.id.mine_exit:
                final MainMsg mainMsg = new MainMsg(mcontext);
                mainMsg.show(mcontext.getWindow().getDecorView(), 0, "是否退出登录？");
                mainMsg.setOnSetSureClickListener(new MainMsg.OnSetSureClickListener() {
                    @Override
                    public void onSure() {
                        if (login_type.equals("1")) {
                            SocialSDK.revokeWeibo(getActivity());

                        } else if (login_type.equals("2")) {

                            SocialSDK.revokeWeChat(getActivity());
                        } else if (login_type.equals("3")) {

                            SocialSDK.revokeQQ(getActivity());
                        }
                        SharedPreferences sp = mcontext.getSharedPreferences(ConstantsUrl.USERDATA, 0);
                        SharedPreferences.Editor editor = sp.edit();
                        editor.clear();
                        editor.commit();
                        mineExit.setVisibility(View.GONE);
                        initData();
                        mainMsg.close();
                    }
                });
                break;
            case R.id.click_resetnetwork_refresh:
                ObjectUtils.GetDataNet(clickResetnetwork, progress, 3);
                initData();
                break;
            case R.id.mine_directbuy_order:
                ToOrder(0, 8);
                break;
            case R.id.mine_service_centre:
                ToObject("客服中心", 0);
                break;
            case R.id.mine_invitation:
//                ToObject("邀请好友", 0);
                if (LoginState.getInstance().isLogin(mcontext)) {
                    ToObject("邀请好友", 0);
                } else {
                    startActivity(new Intent(mcontext, LoginActivity.class));
                }
                break;
            //实名认证
            case R.id.mine_verify:
                if (LoginState.getInstance().isLogin(mcontext)) {
                    startActivity(new Intent(mcontext, VerifyIdCardActivity.class));
                } else {
                    startActivity(new Intent(mcontext, LoginActivity.class));
                }
                //  startActivity(new Intent(mcontext, VerifyIdCardActivity.class));
                break;
            case R.id.mine_newer_guide:

                Intent intent_q = new Intent(getActivity(), NewGuideActivity.class);

                intent_q.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_WEB_URL,ConstantsUrl.baseDomain + "home/www/#/guide");
                intent_q.putExtra("title","新手指南");
                startActivity(intent_q);
                break;
            case R.id.mine_share_bill:
                ToOrder(0, 11);
                break;
            case R.id.ll_coin:
                if (LoginState.getInstance().isLogin(mcontext)) {
                    ToObject("余额明细", 4);
                } else {
                    startActivity(new Intent(mcontext, LoginActivity.class));
                }
                break;
            case R.id.ll_free_coin:
                if (LoginState.getInstance().isLogin(mcontext)) {
                    ToObject("余额明细", 4);
                } else {
                    startActivity(new Intent(mcontext, LoginActivity.class));
                }
                break;
            case R.id.ll_free_sorce:
                if (LoginState.getInstance().isLogin(mcontext)) {
                    ToObject("积分明细", 0);
                } else {
                    startActivity(new Intent(mcontext, LoginActivity.class));
                }
                break;
        }
    }

    private void ToObject(String title, int type) {
        Intent intent_q = new Intent(getActivity(), BaseObject.class);
        intent_q.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_TITLE, title);
        switch (type) {
            case 0:
                break;
            case 1:
                intent_q.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_WEB_URL, "http://pin.lnest.cc/content/index/22");
                break;
            case 2:
                intent_q.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_WEB_URL, "http://pin.lnest.cc/content/index/23");
                break;
            case 3:
                intent_q.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_NEED_ID, commission);
                break;
            case 4:
                intent_q.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_MEMBER_COIN_NUM, coin);
                intent_q.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_MEMBER_FREE_COIN_NUM, free_coin);
                break;

        }

        startActivity(intent_q);
    }

    private void ToOrder(int tab, int type) {
        if (LoginState.getInstance().isLogin(mcontext)) {
            Intent intent = new Intent(mcontext, MainTab.class);
            intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TAB_SORT_SHOW_ID, tab);
            intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_TAB_SORT_SHOW_TYPE, type);
            startActivity(intent);
        } else {
            startActivity(new Intent(mcontext, LoginActivity.class));
        }
    }


}